package com.team.mapper;

import com.team.entity.Competition;
import com.team.vo.CompetitionVo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface CompetitionMapper {
    /**
     * 查询所有比赛信息
     * @return
     */
    List<Competition> getAllCompetitions();

    /**
     * 根据比赛id查询比赛信息
     * @param cid
     * @return
     */
    @Select("select * from competitions where cid=#{cid}")
    Competition getCompetitionDetails(String cid);

    /**
     * 查询该学生报名的所有比赛
     * @param studentId
     * @return
     */
    @Select("SELECT c.name, c.cate, c.time, c.format, c.stage, c.img_src AS imgSrc " +
            "FROM competitions c " +
            "JOIN Registration r ON c.cid = r.cid " +
            "WHERE r.student_id = #{studentId} " +
            "ORDER BY r.priority ASC")
    List<CompetitionVo> getCompetitionsByStudentId(int studentId);

    /**
     * 提交文档时，添加比赛信息（此时为申报阶段）
     * @param competition
     */
    @Insert("INSERT INTO competitions (tid, did,name, cate, time, format, stage, entrants, organizers, entrants_sum, first_choices_sum, img_src, is_top) " +
            "VALUES (#{tid},#{did}, #{name}, #{cate}, #{time}, #{format}, #{stage}, #{entrants}, #{organizers}, #{entrantsSum}, #{firstChoicesSum}, #{imgSrc}, #{isTop})")
    void insert(Competition competition);

    /**
     * 根据文档id查询对应的比赛id
     * @param did
     * @return
     */
    @Select("select cid from competitions where did=#{did}")
    int getCidByDid(int did);

    /**
     * 审核通过时更新比赛状态为开始报名
     * @param cid
     */
    @Update("update competitions set stage='开始报名' where cid=#{cid}")
    void updateCompetitionStage(int cid);

    /**
     * 根据比赛id查询比赛状态（用于判断是否可以报名）
     * @param cid
     * @return
     */
    @Select("SELECT stage FROM competitions WHERE cid = #{cid}")
    String getStage(int cid);

    /**
     * 增加比赛的报名人数
     * @param cid
     */
    @Update("UPDATE competitions SET entrants_sum = entrants_sum + 1 WHERE cid = #{cid}")
    void updateEntrantSum(int cid);

    /**
     * 增加比赛的第一志愿人数
     * @param cid
     */
    @Update("UPDATE competitions SET first_choices_sum = first_choices_sum + 1 WHERE cid = #{cid}")
    void updateFirstSum(int cid);

    /**
     * 减少比赛的参加人数
     * @param cid
     */
    @Update("UPDATE competitions SET entrants_sum = entrants_sum - 1 WHERE cid = #{cid}")
    void decrementEntrantsSum(int cid);

    /**
     * 减少比赛的第一志愿人数
     * @param cid
     */
    @Update("UPDATE competitions SET first_choices_sum = first_choices_sum - 1 WHERE cid = #{cid}")
    void decrementFirstChoicesSum(int cid);
}
